package interfaz;

import automatas.Automata;
import automatas.Arco;
import automatas.Estado;
import automatas.ListaEstados;
import graphviz.GraphViz;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

/**
 * Clase encargada de obtener la imagen del grafo y ponerla en pantalla
 *
 * @author Marco Alvarez
 * @author Sebastian Lena
 */
public class DibujarAutomata extends javax.swing.JFrame {

    private Automata automata;

    /** Creates new form DibujarAutomata
     * @param a Automata a Graficar
     */
    public DibujarAutomata(Automata a) {
        this.automata = a;
        initComponents();
        this.dibujarAutomata();
        Aceptar.requestFocus();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelExpReg = new javax.swing.JLabel();
        jTextFieldExpReg = new javax.swing.JTextField();
        Aceptar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        imagen = new javax.swing.JLabel();

        setTitle("Gráfico Automata");
        setResizable(false);

        jLabelExpReg.setText("Expresión Regular:");

        jTextFieldExpReg.setEditable(false);

        Aceptar.setText("Aceptar");
        Aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AceptarActionPerformed(evt);
            }
        });

        jPanel1.setBackground(javax.swing.UIManager.getDefaults().getColor("Menu.selectionBackground"));

        jScrollPane1.setBackground(javax.swing.UIManager.getDefaults().getColor("Menu.selectionBackground"));
        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Grafico", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 255))); // NOI18N
        jScrollPane1.setViewportView(imagen);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 626, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 502, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(565, Short.MAX_VALUE)
                .addComponent(Aceptar)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelExpReg)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldExpReg, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelExpReg)
                    .addComponent(jTextFieldExpReg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Aceptar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void AceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AceptarActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_AceptarActionPerformed

    /**
     * Setea la Expresion Regular dentro del jTextField
     * @param text Expresion Regular
     */
    public void setExpresion(String text){
        this.jTextFieldExpReg.setText(text);
    }

    /*
     * Metodo que coloca la imagen en el jLabel imagen
     */
    private void dibujarAutomata() {
        this.imagen.setIcon(null);
        ImageIcon i = null;
        i = this.obtenerImagen();

        if (i != null) {
            this.imagen.setIcon(i);
        } else {
            JOptionPane.showMessageDialog(this,
                "Ha ocurrido un error inesperado!",
                "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        this.imagen.setHorizontalAlignment(JLabel.CENTER);
        this.imagen.repaint();
    }

    /*
     * Metodo que obtiene la imagen del GraphViz
     */
    private ImageIcon obtenerImagen() {
        GraphViz graphviz = new GraphViz();
        ImageIcon icon;
        byte [] imagenBytes;
        imagenBytes = graphviz.dibujar(this.generarDot());
        icon = new ImageIcon(imagenBytes);
        return icon;
    }

    /**
     * Genera la sintaxis para la construccion del automata mediante el Graphviz
     * @return Sintaxis Dot
     */
    public String generarDot(){
        String cabecera = "digraph finite_state_machine {\n\trankdir=LR;\n\toverlap=scale;\n";
        String nodos = "\tnode [shape = circle];\n";
        String arcos = "";
        String estilos = "";

        ListaEstados estados = this.automata.getEstados();

        for (Estado e : estados) {
            if(e.isEstadofinal())
                estilos = "[ shape = doublecircle ]";
            else if (e.isEstadoinicial())
                estilos = "[ label = inicio]";
            else
                estilos = "[ shape = circle ]";
            
            nodos+="\t"+e.getId() + " "+estilos+"\n";

            for (Arco enlace : e.getEnlaces()) {

                Estado orig = enlace.getOrigen();
                Estado dest = enlace.getDestino();
                String label = enlace.getEtiqueta();

                String EnlaceStyle = "[ label = \"" + label + "\" ]";

                arcos += "\t"+orig.getId() + " -> " + dest.getId() +
                                " "+EnlaceStyle+"\n";
            }
        }
        String result = cabecera + nodos + arcos + "}";
        return result;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Aceptar;
    private javax.swing.JLabel imagen;
    private javax.swing.JLabel jLabelExpReg;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextFieldExpReg;
    // End of variables declaration//GEN-END:variables

}
